const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 检查是否已经安装了依赖
const nodeModulesPath = path.join(__dirname, 'node_modules');
const packageLockPath = path.join(__dirname, 'package-lock.json');

console.log('Checking if backend dependencies are installed...');

if (!fs.existsSync(nodeModulesPath) || !fs.existsSync(packageLockPath)) {
  console.log('Installing backend dependencies...');
  try {
    // 使用 Electron 的 Node.js 可执行文件路径来执行 npm install
    const nodePath = process.execPath;
    const npmPath = nodePath.replace('electron.exe', 'node_modules\\npm\\bin\\npm-cli.js');
    
    // 如果找不到 npm-cli.js，则使用 node -c "require('child_process').execSync('npm install --production', { stdio: 'inherit' })"
    if (fs.existsSync(npmPath)) {
      spawnSync(nodePath, [npmPath, 'install', '--production'], { 
        cwd: __dirname,
        stdio: 'inherit'
      });
    } else {
      // 备用方案：直接使用 node 执行命令
      spawnSync(nodePath, ['-e', 'require("child_process").execSync("npm install --production", { stdio: "inherit" })'], { 
        cwd: __dirname,
        stdio: 'inherit'
      });
    }
    console.log('Backend dependencies installed successfully!');
  } catch (error) {
    console.error('Failed to install backend dependencies:', error.message);
    process.exit(1);
  }
} else {
  console.log('Backend dependencies already installed.');
}